package com.itheima.config;

import com.itheima.dto.UserDTO;
import com.itheima.enums.MsgCode;
import com.itheima.exceptions.CustomException;
import com.itheima.utils.CurrentUser;
import com.itheima.utils.ResultUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @Description: 自定义注解参数解析器
 * @Date :2019-08-24 14:52
 * @Author : yuan_he_song
 */
@Component
public class CurrentUserArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
                 /** 判断是否能转成UserDTO类型  @CurrentUser UserDTO */
        return  methodParameter.getParameterType().isAssignableFrom(UserDTO.class)
                 /** 是否有CurrentUser注解 */
              && methodParameter.hasMethodAnnotation(CurrentUser.class);
    }

    @Override /** 在这里我们直接把放在session中的用户信息放回去即可 */
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        UserDTO userDTO = (UserDTO) webRequest.getAttribute(ResultUtils.CURRENT_USER, RequestAttributes.SCOPE_SESSION);
        if(userDTO != null){
            return userDTO;
        }
        throw new CustomException(MsgCode.ERROR_USER_NAME);
    }


}
